
using System.Collections.Generic;
/// <summary>
/// 列表字典，专门针对又要遍历，又要查询key的情况，相比Dictionary提升6倍性能
/// 注意：value只能放自定义数据，不能放string,int,float等值类型，如果一定要放，就不能修改list里面的值，否则会不同步
/// </summary>
public class DictExt<Key, Value> : BaseObject, IClear
{
    public Dictionary<Key, Value> dict;
    public List<Value> list;

    private int _count = 0;

    public DictExt(int capacity = 0)
    {
        this.Init(capacity);
    }

    protected virtual void Init(int capacity)
    {
        if (this.dict == null)
        {
            this.dict = new Dictionary<Key, Value>(capacity);
        }
        if (this.list == null)
        {
            this.list = new List<Value>(capacity);
        }
    }

    public void Add(Key key, Value value)
    {
        Value item;
        if (!this.dict.TryGetValue(key, out item))
        {
            this.dict.Add(key, value);
            this.list.Add(value);
            _count++;
        }
        else
        {
            this.dict[key] = value;
            int idx = this.list.IndexOf(item);
            if (idx >= 0)
                this.list[idx] = value;
        }
    }

    public Value Remove(Key key)
    {
        Value item;
        if (dict.TryGetValue(key, out item))
        {
            dict.Remove(key);
            list.Remove(item);
            _count--;
        }
        return item;
    }

    public void Clear()
    {
        dict.Clear();
        list.Clear();
        _count = 0;
    }

    public override void Dispose()
    {
        base.Dispose();
        this.dict = null;
        this.list = null;
    }

}